<template>
  <div class="login-wrap">
    <div class="login-box">
      <h1 class="tit">Hello</h1>
      <el-form :rules="rules" label-width="0" ref="loginForms" :mode="formData">
        <el-form-item label="" prop="username">
          <el-input :prefix-icon="User" v-model="formData.username" />
        </el-form-item>
        <el-form-item label="" prop="password">
          <el-input
            type="password"
            :prefix-icon="Lock"
            v-model="formData.password"
          />
        </el-form-item>
        <el-form-item label="">
          <el-button type="primary" class="w100" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue'
import { reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElNotification } from 'element-plus'
//引入获取当前时间的函数
import { getTime } from '@/utils/time'
//引入用户相关的小仓库
import useUserStore from '@/store/modules/user'
let useStore = useUserStore()
//获取el-form组件
let loginForms = ref()
//获取路由器
let $router = useRouter()
//路由对象
let $route = useRoute()
//定义变量控制按钮加载效果
let loading = ref(false)
//收集账号与密码的数据
let formData = reactive({ username: 'admin', password: 'atguigu123' })
//登录按钮回调
const login = async () => {
  await loginForms.value.validate()
  //加载效果:开始加载
  loading.value = true
  try {
    //保证登录成功
    let res = await useStore.userLogin(formData)
    console.log('res: ', res)
    let redirect: any = $route.query.redirect
    $router.push({ path: redirect || '/' })
    ElNotification({
      type: 'success',
      message: '欢迎回来',
      title: `HI,${getTime()}好`,
    })
    loading.value = false
  } catch (error) {
    loading.value = false
    ElNotification({
      type: 'error',
      message: (error as Error).message,
    })
  }
}
const rules = {
  username: [
    { required: true, message: '请输入账号', trigger: ['change', 'blur'] },
    {
      required: true,
      min: 5,
      max: 12,
      message: '账号长度5-12位',
      trigger: ['change', 'blur'],
    },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: ['change', 'blur'] },
    {
      required: true,
      min: 5,
      max: 12,
      message: '密码长度5-12位',
      trigger: ['change', 'blur'],
    },
  ],
}
</script>
<style scoped lang="scss">
.login-wrap {
  width: 100%;
  height: 100vh;
  position: relative;
  background: linear-gradient(rgb(123, 155, 234), rgb(88, 101, 164));
  .login-box {
    width: 280px;
    height: 260px;
    background: #fff;
    border-radius: 10px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    padding: 20px 14px;
  }
  .tit {
    margin-bottom: 20px;
  }
  .w100 {
    width: 100%;
  }
}
</style>
